package com.kuaimacode.kframework.agent.controller.order;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.agent.services.agent.SysAgentService;
import com.kuaimacode.kframework.agent.services.master.MasterService;
import com.kuaimacode.kframework.agent.services.order.OrderDispatchService;
import com.kuaimacode.kframework.agent.services.order.OrderService;
import com.kuaimacode.kframework.agent.services.sysparam.SysParamService;
import com.kuaimacode.kframework.agent.services.user.UserService;
import com.kuaimacode.kframework.agent.util.SessionUtil;
import com.kuaimacode.kframework.agent.vo.response.OrderRefuse;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.mybatis.models.agent.SysAgent;
import com.kuaimacode.kframework.mybatis.models.master.MasterWaitResp;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.sysparam.SysParam;
import com.kuaimacode.kframework.mybatis.models.user.*;
import com.kuaimacode.kframework.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 订单调度台
 * @author 中元
 * @date 2019/03/18
 */

/**
 * Controller
 */
@Controller
@RequestMapping({"/orderDispatch"})
public class OrderDispatchController {
	private static String PAGE_FILE_NAME = "orderDispatch/";

	@Autowired
	private OrderService orderServices;

	@Autowired
	private SysAgentService agentServices;

	@Autowired
	private MasterService masterServices;

	@Autowired
	private OrderDispatchService orderDispatchService;

	@Autowired
	private SysParamService sysParamService;
	@Autowired
	private UserService userService;


	@RequestMapping(value = {"/index"})
	public String index(
			@RequestParam(value = "pageNum", required = false, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
			@RequestParam(value = "pageSize", required = false, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize, ModelMap model
			) {
		String agentId = SessionUtil.getAgentId();
		//pageNum = Optional.ofNullable(pageNum).orElse(10000);
		//pageSize = Optional.ofNullable(pageSize).orElse(1);
		//查询所有跑腿的待接单订单
		//PageInfo<OrderSimple> pageInfo = orderServices.queryAllOrders(null, Constant.OrderStatusEnum.WAIT_ACCEPT.getCode(), 1, pageNum, pageSize, agentId);
		List<OrderSimple> pageInfo = orderServices.queryAllOrdersNoPage(null, Constant.OrderStatusEnum.WAIT_ACCEPT.getCode(), null,  agentId);
		//查询分站
		SysAgent agent = agentServices.getById(agentId);
		//查询所有在接单中的师傅
		//List<MasterWaitResp> datas = masterServices.findWaitMaster(null,agentId,null,null,"1",null,"1", "1");
		// pageInfo.list order
		if(agent.getDispatchType() == null){
			agent.setDispatchType("person");
			agentServices.updateById(agent);
		}
		List<OrderSimple> list = new ArrayList<>();
		pageInfo.stream().forEach(order->{
			//过滤技术服务中指定师傅下单的订单
			if(!(order.getOrderType() != Constant.OrderTypeEnum.PAO_TUI.getCode() && order.getMasterId() !=null)){
				//查看是否已派单，且是待接单
				OrderDispatch orderDispatch = orderDispatchService.getByOrderId(order.getOrderId(), 1);
				if(orderDispatch != null){
					order.setAudio("1");//已经派单
				}
				list.add(order);
			}
		});

		model.put("pageInfo", list);
		model.put("agent", agent);
		//model.put("masterList", datas);
		return PAGE_FILE_NAME + "index";
	}

	/**
	 * 为起始地址都有的订单匹配师傅
	 * @param type
	 * @param childType
	 * @param fromLongitude
	 * @param fromLatitude
	 * @param toLongitude
	 * @param toLatitude
	 * @param map
	 * @return
	 */
    @RequestMapping(value = {"/selectMasterAll"}, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult selectMasterAll(String type, String childType, String fromLongitude, String fromLatitude, String toLongitude, String toLatitude, ModelMap map) {
        try {
        	Double maxDistance = 5d;//订单起始地点5公里范围内的师傅
            String agentId = SessionUtil.getAgentId();
			List<MasterWaitResp> lists = new ArrayList<MasterWaitResp>();
			Double orderLatitude = Double.parseDouble(fromLatitude);
			Double orderLongitude = Double.parseDouble(fromLongitude);
			Double orderToLatitude = Double.parseDouble(toLatitude);
			Double orderToLongitude = Double.parseDouble(toLongitude);
            //查询所有在接单中的师傅
            List<MasterWaitResp> datas = masterServices.findWaitMaster(null,agentId,null,null,"1",null,"1", "1");
            datas.stream().forEach(master->{
				//查询订单类型匹配的师傅
				Map mapTypes = JSON.parseObject(master.getSkillType());
				for (Object obj : mapTypes.keySet()){
					System.out.println("key为："+obj+"值为："+mapTypes.get(obj));
				}
				if(mapTypes.containsKey(type)){
					String tempChildType = (String)mapTypes.get(type);
					if(type.equals("1") || (tempChildType != null && tempChildType.indexOf(childType)>=0)){
						//查询订单起点5公里范围内的师傅
						Double tempDistance = CommonUtil.getDistance(orderLatitude, orderLongitude,
								Double.parseDouble(master.getLatitude()), Double.parseDouble(master.getLongitude()));
						tempDistance = tempDistance/1000;
						if(tempDistance != null && tempDistance <= maxDistance){
							//计算匹配度（订单起始距离与师傅已接订单起始距离相加/2的最小值）
							List<OrderSimple> masterOrders = orderServices.findMasterOrders(master.getMasterId());
							//final  Integer path = 0;//匹配度
							master.setPath(0);
							if(masterOrders != null && masterOrders.size()>0){
								master.setOrderCount(masterOrders.size());
								masterOrders.stream().forEach(order->{
									//起始地址都不为空
									if(order.getFromAddress() != null && order.getToAddress() !=null){
										Double tempFromLatitude = Double.parseDouble(order.getFromLatitude());
										Double tempFromLongitude = Double.parseDouble(order.getFromLongitude());
										Double tempFromDis = CommonUtil.getDistance(orderLatitude,orderLongitude, tempFromLatitude, tempFromLongitude);
										tempFromDis = tempFromDis/1000;
										Double tempToLatitude = Double.parseDouble(order.getToLatitude());
										Double tempToLongitude = Double.parseDouble(order.getToLongitude());
										Double tempToDis = CommonUtil.getDistance(orderToLatitude,orderToLongitude, tempToLatitude, tempToLongitude);
										tempToDis = tempToDis/1000;
										Integer tempPath = (int)(tempFromDis+tempToDis)/2;
										if(master.getPath() == 0){
											master.setPath(tempPath);
										}else{
											if(tempPath < master.getPath()){
												master.setPath(tempPath);
											}
										}
									}
								});
							}else{
								master.setPath(0);//匹配度为0
							}
							lists.add(master);
						}
					}
				}
			});

            return JsonResult.success(lists);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
    }

	/**
	 * 为只有起或始地址的订单匹配师傅
	 * @param type
	 * @param childType
	 * @param longitude
	 * @param latitude
	 * @param map
	 * @return
	 */
	@RequestMapping(value = {"/selectMaster"}, method = RequestMethod.GET)
	@ResponseBody
	public JsonResult selectMaster(String type, String childType, String longitude, String latitude, ModelMap map) {
		try {
			Double maxDistance = 5d;//订单起始地点5公里范围内的师傅
			String agentId = SessionUtil.getAgentId();
			List<MasterWaitResp> lists = new ArrayList<MasterWaitResp>();
			Double orderLatitude = Double.parseDouble(latitude);
			Double orderLongitude = Double.parseDouble(longitude);
			//查询所有在接单中的师傅
			List<MasterWaitResp> datas = masterServices.findWaitMaster(null,agentId,null,null,"1",null,"1", "1");
			datas.stream().forEach(master->{
				//查询订单类型匹配的师傅
				Map mapTypes = JSON.parseObject(master.getSkillType());
				for (Object obj : mapTypes.keySet()){
					System.out.println("key为："+obj+"值为："+mapTypes.get(obj));
				}
				if(mapTypes.containsKey(type)){
					String tempChildType = (String)mapTypes.get(type);
					if(type.equals("1") || (tempChildType != null && tempChildType.indexOf(childType)>=0)){
					//if( (tempChildType != null && childType != null && tempChildType.indexOf(childType)>=0)){

						List<OrderSimple> masterOrders = orderServices.findMasterOrders(master.getMasterId());
						if(masterOrders != null && masterOrders.size()>0){
							master.setOrderCount(masterOrders.size());
						}
						//查询订单起点5公里范围内的师傅
						Double tempDistance = CommonUtil.getDistance(orderLatitude, orderLongitude,
								Double.parseDouble(master.getLatitude()), Double.parseDouble(master.getLongitude()));
                        tempDistance = tempDistance/1000;
						if(tempDistance != null && tempDistance <= maxDistance){
							master.setPath(tempDistance.intValue());//匹配度为0
							lists.add(master);
						}
					}
				}
			});

			return JsonResult.success(lists);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.failure(e.getMessage());
		}
	}

	@RequestMapping(value = {"/dispatchType"}, method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public JsonResult dispatchType(String dispatchType) {
		try {
			String agentId = SessionUtil.getAgentId();
			SysAgent agent = agentServices.getById(agentId);
			if(agent == null){
				return JsonResult.failure("操作失败");
			}
			agent.setDispatchType(dispatchType);
			if(agentServices.updateById(agent)){
				return JsonResult.success("操作成功");
			}else{
				return JsonResult.failure("操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.failure(e.getMessage());
		}

	}

	@RequestMapping(value = {"/dispatch"}, method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public JsonResult dispatch(Long masterId, Long orderId) {
		try {
			Order order  = orderServices.getById(orderId);
			UserMaster um = masterServices.findByUserId(masterId);
			if(order == null || um == null){
				return JsonResult.failure("订单或者师傅不存在");
			}

            //获取师傅最大接单笔数
            QueryWrapper<SysParam> query = new QueryWrapper<>();
            query.eq("name","MASTER_ORDER_LIMIT");
            SysParam param = sysParamService.getOne(query);
            if (param !=null&& StringUtils.isNotEmpty(param.getValue())){
                List<Integer> statusList = new ArrayList<>();
                statusList.add(Constant.OrderStatusEnum.SERVERING.getCode());
                statusList.add(Constant.OrderStatusEnum.FETCHING.getCode());
                statusList.add(Constant.OrderStatusEnum.SENDING.getCode());
                List<OrderNear> orders = orderServices.getOrderByStatusList(um.getUserId(), statusList);
                if (CollectionUtils.isNotEmpty(orders) && orders.size() >= Integer.parseInt(param.getValue())) {
                    return JsonResult.failure("师傅最多同时接"+param.getValue()+"单!");
                }
            }

			if(order.getStatus()>Constant.OrderStatusEnum.WAIT_ACCEPT.getCode()){
				return JsonResult.failure("订单已被接单");
			}
			if(order.getDispatchMaster() != null && order.getMasterId() != null){
				return JsonResult.failure("订单已被派单或者抢单");
			}
			OrderDispatch orderDispatch = orderDispatchService.getByOrderId(orderId, 1);
			if(orderDispatch == null){
				orderDispatch = new OrderDispatch();
			}else{
				return JsonResult.failure("订单正在派单中！");
			}
			orderDispatch.setCreateAt(new Date());
			orderDispatch.setDispatchBy(SessionUtil.getUserId());
			orderDispatch.setMasterId(masterId);
			orderDispatch.setOrderId(orderId);
			orderDispatch.setAgentId(order.getAgentId());
			orderDispatch.setOrderNo(order.getOrderNo());
			orderDispatch.setStatus(1);//状态 1-待接单 2-已接单 3-已拒绝
			if(orderDispatchService.saveOrUpdate(orderDispatch)){
				order.setDispatchMaster(masterId);//派单
				order.setUpdateAt(new Date());
				orderServices.updateById(order);
				return JsonResult.success("派单成功，请等待师傅接单，如果30分钟内未接单则订单取消");
			}else{
				return JsonResult.failure("派单失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.failure(e.getMessage());
		}

	}



	@RequestMapping(value = {"/refuseList"})
	public String refuseList(
			@RequestParam(value = "pageNum", required = false, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
			@RequestParam(value = "pageSize", required = false, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize, ModelMap model
	) {
		String agentId = SessionUtil.getAgentId();
		pageNum = Optional.ofNullable(pageNum).orElse(1);
		pageSize = Optional.ofNullable(pageSize).orElse(10);
		//查询所有跑腿的待接单订单
		PageInfo<OrderDispatch> pageInfo = orderDispatchService.findAll(pageNum, pageSize, agentId, 3);//所有拒绝的派单
		//查询分站
		//SysAgent agent = agentServices.getById(agentId);
		PageInfo<OrderRefuse> pageInfo1 = new PageInfo<>();

		List<OrderRefuse> list = new ArrayList<>();
		pageInfo.getList().stream().forEach(order->{
			Order or = orderServices.getById(order.getOrderId());
			if(or != null ){
				OrderRefuse orderRefuse = new OrderRefuse();
				BeanUtils.copyProperties(or, orderRefuse);

				UserMaster master = masterServices.findByUserId(order.getMasterId());
				User user = userService.getById(order.getMasterId());

				if(master != null && user != null){
					orderRefuse.setMasterId(order.getMasterId());
					orderRefuse.setMasterName(master.getMasterName());
					orderRefuse.setMasterPhone(user.getPhone());
					orderRefuse.setDispatchDate(order.getCreateAt());
					orderRefuse.setDispatchId(order.getId());
					/*if(or.getStatus() > Constant.OrderStatusEnum.WAIT_ACCEPT.getCode()){
						//已接单
						orderRefuse.setStatus(2);
					}else{
						if(order.getDealStatus() == 2){
							orderRefuse.setStatus(2);//yi处理
						}else{
							orderRefuse.setStatus(1);//未处理
						}
					}*/
					if(order.getDealStatus() == 2){
						orderRefuse.setStatus(2);//yi处理
					}else{
						orderRefuse.setStatus(1);//未处理
					}
					list.add(orderRefuse);
				}
			}
		});
		pageInfo1.setList(list);
		model.put("pageInfo", pageInfo1);
		//model.put("agent", agent);
		return PAGE_FILE_NAME + "refuseList";
	}

	@RequestMapping(value = {"/dealRefuse"}, method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public JsonResult dealRefuse(Long dispatchId) {
		try {
			OrderDispatch orderDispatch  = orderDispatchService.getById(dispatchId);
			if(orderDispatch == null ){
				return JsonResult.failure("数据不存在");
			}
			orderDispatch.setDealStatus(2);
			if(orderDispatchService.saveOrUpdate(orderDispatch)){
				return JsonResult.success("操作成功");
			}else{
				return JsonResult.failure("操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.failure(e.getMessage());
		}

	}
}
